//
//  PicturePickerCollection.swift
//  图片选择
//
//  Created by wulei on 15/12/18.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit

private let picturePickerCellID = "picturePickerCellID"
private let picturePickerMaxCount = 3

class PicturePickerCollection: UICollectionViewController {
    // 定义一个懒加载数组
     lazy var pictures = [UIImage]()
    // 当前用户选中的图片索引
    private var selectedIndex = 0
    
    // MARK: - controller 构造方法
    init() {
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

        // 注册重用 Cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerCellID)


    }
    
    
    
    
    // MARK: - Layout 流水布局
    private class PicturePickerLayout: UICollectionViewFlowLayout {

        private override func prepareLayout() {
            super.prepareLayout()
            
            let count: CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            sectionInset = UIEdgeInsetsMake(margin,margin,0,margin)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            
        
        }
        
    }

}

// MARK: - 数据源方法 UICollectionViewDataSource
extension PicturePickerCollection {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + (pictures.count == picturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerCellID, forIndexPath: indexPath) as! PicturePickerCell
        
        cell.image = (indexPath.item < pictures.count ) ? pictures[indexPath.item] : nil
        cell.pictureDelegate = self
        
        return cell
    }

}


// MARK: - 实现代理方法 UIImagePickerController
extension PicturePickerCollection: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    
    // 实现这个代理方法,必须自己 dismissViewController
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleToWidth(600)
        
        if selectedIndex >= pictures.count {

            pictures.append(scaleImage)
        }else {

            pictures[selectedIndex] = scaleImage
        }
        
        collectionView?.reloadData()
        
        
        // 释放控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
}


// MARK: - 实现代理方法 addButton / removeButton
extension PicturePickerCollection: PicturePickerCellDelegate {
    // 添加图片
   @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        
    // 判断是否允许访问图片 UIImagePickerControllerSourceType
    if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
        print("无法访问照片库")
        return
        
    }
    
    // 记录当前用户选中的图片索引
    selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0

    
    let pickerView = UIImagePickerController()
    pickerView.delegate = self
    
    presentViewController(pickerView, animated: true, completion: nil)
    
    }
    
    // 删除图片
   @objc private func picturePickerCellDidRemove(cell: PicturePickerCell){
    
    let indexPath = collectionView!.indexPathForCell(cell)!
    if indexPath.item >= pictures.count {
        return
    }
    
    pictures.removeAtIndex(indexPath.item)
    
//    collectionView?.reloadData()
    collectionView?.deleteItemsAtIndexPaths([indexPath])
    }
}

// MARK: - 定义代理方法
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
    // 添加图片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    // 删除图片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}


// MARK: - 自定义picturePickerCell
 private class PicturePickerCell: UICollectionViewCell {
    
   weak var pictureDelegate: PicturePickerCellDelegate?
    
    
    var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            removeButton.hidden = (image == nil)
        }
    }
    // MARK: - 监听方法
   @objc func addPicture() {
    
    pictureDelegate?.picturePickerCellDidAdd?(self)
    
    }
    
   @objc func removePicture() {
    pictureDelegate?.picturePickerCellDidRemove?(self)
    
    }
    
    // cell 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        addButton.contentMode = .ScaleAspectFill
        
        
        // 设置约束
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addButton.snp_top)
            make.right.equalTo(addButton.snp_right)
        }
        
        
    }
    
    // 懒加载控件
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}